from 第8天作业解答.getLogger import Logger

logObj = Logger("login")
logger = logObj.getLogger()

with open('./register.txt', 'r', encoding='utf-8') as f:
    dataLineList = f.read().split('\n')
    userList = [
        data.split('|')
        for data in dataLineList
        if data
    ]

def login():
    userCount = {}
    while True:
        username = input("username: ")
        password = input("password: ")

        for user in userList:
            if username == user[0]:

                if not userCount.get(username):
                    userCount[username] = {'count': 0}

                if password == user[1]:
                    return True
                else:
                    if userCount[username]['count'] == 2:
                        return False
                    else:
                        userCount[username]['count'] += 1
                        logger.error("密码不正确，请重新输入")
                break
        else:
            logger.error("您输入的用户名不存在")

# login()


def register():
    while True:
        username = input("username: ")
        password = input("password: ")
        for user in userList:
            if username == user[0]:
                logger.error("您输入的用户名已被注册")

        else:
            with open('./register.txt', 'a+', encoding='utf-8') as f:
                try:
                    f.seek(0)
                    data = f.read()
                    writeText = ''
                    if data:
                        if data[-1] != '\n':
                            writeText = '\n'
                    f.write(f"{writeText}{username}|{password}\n")
                    return True
                except:
                    return False

register()